package com.liull.netty.nio.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 11:23 2021/7/25
 * @Modified By:
 */
@Slf4j
public class HttpServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            final ChannelFuture future = sb.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new HttpServerCodec());
                            // ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            // @Override
                            // public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // super.channelActive(ctx);
                            // }
                            //
                            // @Override
                            // public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            // super.channelRead(ctx, msg);
                            // log.debug("{}", msg.getClass());
                            // // 需要分别处理 可以采用SimpleChannelInboundHandler 只处理某一种类型消息
                            // if (msg instanceof HttpRequest) {
                            //
                            // } else if (msg instanceof HttpContent) {
                            //
                            // }
                            // }
                            // });
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
                                    log.debug("uri:{}, method:{}", request.uri(), request.method());
                                    // 构造响应内容返回给客户端
                                    DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
                                    final byte[] bytes = "Hello.".getBytes();
                                    response.content().writeBytes(bytes);
                                    response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
                                    ctx.channel().writeAndFlush(response);
                                }
                            });
                        }
                    }).bind(8989).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
